﻿using MySql.Data.MySqlClient;
using RantopadService.Business;
using RantopadService.Conn;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RantopadService.ClientWeb
{
    public partial class ResetPSW : System.Web.UI.Page
    {
        private string email = "";
        private string resetTM = "";

        protected void Page_Load(object sender, EventArgs e)
        {
     
                email = CodeBusiness.Decode( Request.QueryString["email"]);
                resetTM = CodeBusiness.Decode(Request.QueryString["tm"]);
                checkPara(email, resetTM);

   
            
        }

        private void checkPara(string email, string resetTM)
        {
            string sql = "select * from resetpsw where  email='" + email.Trim() + "' and tm='" + resetTM.Trim() + "' and CHANGED='0' ";
            DataTable dt = new DataTable();
            var myconnection = MyMySqlHelper.GetConn();
            myconnection.Open();
            var dataAdapter = new MySqlDataAdapter(sql, myconnection);
            myconnection.Close();
            dataAdapter.Fill(dt);
            if (dt.Rows.Count < 1)
            {
                Response.Write("<script>alert('地址错误，请重新申请。');</script>");
                Response.Write("<script>window.opener=null;window.close();</script>");
            }
            else
            {
                if ((Convert.ToDateTime(resetTM) - DateTime.Now).Days > 1)//如果超过一定时间没有进行更改密码的操作，更改密码的链接失效
                {
                    Response.Write("<script>alert('地址失效，请重新申请。。');</script>");
                    Response.Write("<script>window.opener=null;window.close();</script>");
                }

            }
            
        }

        protected void BtnResetPSW_Click(object sender, EventArgs e)
        {
            if(psw.Text==""||psw2.Text=="")
            {
                Response.Write("<script>alert('密码不能为空！')</script>");
                return;
            }
            if (psw.Text != psw2.Text)
            {
                Response.Write("<script>alert('两次密码不一致！')</script>");
                return;
            }
            if(UserBusiness.updateUserPswByEmail(email,MD5Helper.GetMd5Str( psw.Text.Trim()))>0)
            {
                string mysql = "update `resetpsw` set `CHANGED`='1'  where `email`='{0}' and tm='{1}'";
                mysql = string.Format(mysql, email, resetTM);
                //创建数据库连接
                var myconnection = MyMySqlHelper.GetConn();
                myconnection.Open();
                MySqlCommand mycommand = new MySqlCommand(mysql, myconnection);
                mycommand.ExecuteNonQuery();
                myconnection.Close();
                Response.Write("<script>alert('修改成功，请牢记新密码！')</script>");
                Response.Write("<script>window.opener=null;window.close();</script>");
            }
        }
    }
}